package com.xulinhao.msmservice.controller;/**
 * @author xulinhao
 * @create 2021-09-06 21:59
 */

import com.xulinhao.commonutils.R;
import com.xulinhao.msmservice.service.MsmService;
import com.xulinhao.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author xlh
 * @packagename: com.xulinhao.msmservice.controller
 * @classname: MsmController
 * @Description:
 * @Date 2021/9/6
 */
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //从Redis获取验证码,如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //如果获取不到,则进行阿里云的发送
        //生成随机值,传递阿里云发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param,phone);
        if (isSend) {
            //发送成功,把发送成功的验证码放到Redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }
}
